﻿using AnQinFrameWorkAPI.DataBase;
using AnQinFrameWorkAPI.Entity.SystemCore.DTO.Menu;
using AnQinFrameWorkAPI.Entity.SystemCore.Entity;
using AnQinFrameWorkAPI.Entity.SystemCore.View.Menu;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using FrameWork.DataHelper;
using FrameWork.Entity;
using FrameWork.JWT;
using FrameWork.Request;
using Microsoft.EntityFrameworkCore;

namespace AnQinFrameWorkAPI.Service.SystemCore;

/// <summary>
///     菜单业务层
/// </summary>
public class MenuService
{
    #region 获取菜单列表

    public async Task<RequestResponseModel> GetMenuList(MenuSearchDTO menuSearchDto)
    {
        //筛选
        var query = _context.Menu
            .ProjectTo<MenuView>(_mapper.ConfigurationProvider)
            .WhereIF(a => a.Name.Contains(menuSearchDto.Name),
                !string.IsNullOrEmpty(menuSearchDto.Name))
            .WhereIF(a => a.Url.Contains(menuSearchDto.Url), !string.IsNullOrEmpty(menuSearchDto.Url))
            .WhereIF(a => a.IsShow == menuSearchDto.IsShow, menuSearchDto.IsShow != null)
            .WhereIF(a => a.IsEnable == menuSearchDto.IsEnable, menuSearchDto.IsEnable != null)
            .AsNoTracking();

        //返回列表
        var menuList = await query
            .OrderBy(a => a.Order)
            .ToListAsync();

        //返回数据
        return RequestResponse.OK(menuList, "查询成功");
    }

    #endregion

    #region 获取菜单详情列表

    public async Task<RequestResponseModel> GetMenuDetailList(MenuSearchDTO menuSearchDto)
    {
        //直接返回列表
        var menuList = await _context.Menu
            .ProjectTo<MenuDetailView>(_mapper.ConfigurationProvider)
            .WhereIF(a => a.Name.Contains(menuSearchDto.Name),
                !string.IsNullOrEmpty(menuSearchDto.Name))
            .WhereIF(a => a.Url.Contains(menuSearchDto.Url), !string.IsNullOrEmpty(menuSearchDto.Url))
            .WhereIF(a => a.IsShow == menuSearchDto.IsShow, menuSearchDto.IsShow != null)
            .WhereIF(a => a.IsEnable == menuSearchDto.IsEnable, menuSearchDto.IsEnable != null)
            .AsNoTracking().ToListAsync();

        //返回数据
        return RequestResponse.OK(menuList, "查询成功");
    }

    #endregion

    #region 获取用户菜单列表

    public async Task<RequestResponseModel> GetUserMenuDetailList()
    {
        //查询用户角色
        var roleList = _context.StaffRole
            .Where(a => a.StaffId.ToString() == _userContext.UserId)
            .Select(a => a.RoleId.ToString())
            .AsNoTracking()
            .ToList();

        //查询角色菜单
        var roleMenuList = _context.RoleMenu
            .Where(a => roleList.Contains(a.RoleId.ToString()))
            .Select(a => a.MenuId.ToString())
            .AsNoTracking()
            .ToList();

        //返回用户菜单列表
        var menuList = await _context.Menu
            .ProjectTo<MenuDetailView>(_mapper.ConfigurationProvider)
            .Where(a => roleMenuList.Contains(a.Id.ToString()))
            .AsNoTracking().ToListAsync();

        //返回数据
        return RequestResponse.OK(menuList, "查询成功");
    }

    #endregion

    #region 新增菜单

    public async Task<RequestResponseModel> AddMenu(MenuAddDTO menuAddDto)
    {
        //生成新数据
        var menu = _mapper.Map<MenuModel>(menuAddDto);

        menu.Id = Guid.NewGuid();
        menu.CreateTime = DateTime.Now;

        //新增数据
        _context.Menu.Add(menu);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(menu.Id, "新增成功");
    }

    #endregion

    #region 编辑菜单

    public async Task<RequestResponseModel> PutMenu(MenuUpdateDTO menuUpdateDto)
    {
        //校验数据
        var query = await Valid.ValidId(_context.Menu, menuUpdateDto.Id);
        if (query == null) return RequestResponse.ErrorRequest("菜单Id无效");

        //编辑数据
        var menu = _mapper.Map(menuUpdateDto, query);

        //更新表
        _context.Menu.Update(menu);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(menuUpdateDto.Id);
    }

    #endregion

    #region 删除菜单

    public async Task<RequestResponseModel> DeleteMenu(SingleIdDTO singleIdDto)
    {
        //校验数据
        var query = await Valid.ValidId(_context.Menu, singleIdDto.Id);
        if (query == null) return RequestResponse.ErrorRequest("菜单Id无效");

        //校验该菜单下是否有子菜单
        var menu = await _context.Menu
            .AsNoTracking()
            .Where(x => x.SuperiorId.ToString() == singleIdDto.Id)
            .ToListAsync();

        //如果有则返回
        if (menu.Count > 0) return RequestResponse.BadRequest("该菜单下还有子菜单，无法删除");
        ;

        //删除操作
        _context.Menu.Remove(query);

        //保存库
        await _context.SaveChangesAsync();
        return RequestResponse.OK(singleIdDto.Id, "删除成功");
    }

    #endregion

    #region 初始化

    //数据库
    private readonly DatabaseContext _context;

    //自动映射
    private readonly IMapper _mapper;

    //解密token
    private readonly IUserContext _userContext;

    //构造注入
    public MenuService(IUserContext userContext, DatabaseContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
        _userContext = userContext;
    }

    #endregion
}